package com.quanfaqiang.demo1.service.impl;


import com.quanfaqiang.demo1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class WebSocketHandlerImpl extends TextWebSocketHandler {

    @Autowired
    private UserService userService;  // 注入 UserService，用于更新用户状态到数据库

    // 存储在线用户的 WebSocket 会话
    private final Map<String, WebSocketSession> activeUsers = new ConcurrentHashMap<>();

    public WebSocketHandlerImpl(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userId = session.getUri().getQuery().split("=")[1];  // 假设通过查询参数传递 userId
        activeUsers.put(userId, session);  // 将用户加入到在线用户列表中

        // 更新用户状态到数据库
        userService.updateUserStatus(Integer.parseInt(userId), "online");

        sendUserStatus(userId, "online");  // 发送在线状态消息
        System.out.println("用户 " + userId + " 已连接");
    }

    @Override
    public void handleTextMessage(WebSocketSession session, org.springframework.web.socket.TextMessage message) throws Exception {
        // 处理前端发送的消息
        String msg = message.getPayload();
        System.out.println("收到消息: " + msg);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        String userId = session.getUri().getQuery().split("=")[1];  // 获取用户 ID
        activeUsers.remove(userId);  // 从在线用户列表中移除

        // 更新用户状态到数据库
        userService.updateUserStatus(Integer.parseInt(userId), "offline");

        sendUserStatus(userId, "offline");  // 发送离线状态消息
        System.out.println("用户 " + userId + " 已断开连接");
    }

    private void sendUserStatus(String userId, String status) throws Exception {
        WebSocketSession session = activeUsers.get(userId);
        if (session != null && session.isOpen()) {
            session.sendMessage(new org.springframework.web.socket.TextMessage("{\"status\": \"" + status + "\", \"userId\": \"" + userId + "\"}"));
        }
    }
}
